import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_application/app/app.dart';
// import 'package:in_app_purchase/in_app_purchase.dart';
// import 'package:in_app_purchase_android/in_app_purchase_android.dart';
// import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart';

// // Auto-consume must be true on iOS.
// // To try without auto-consume on another platform, change `true` to `false` here.
final bool _kAutoConsume = Platform.isIOS || true;
const String _kConsumableId = 'consumable';

class CombatPurchasePage extends StatefulWidget {
  const CombatPurchasePage({super.key});

  @override
  State<CombatPurchasePage> createState() => _CombatPurchasePageState();
}

class _CombatPurchasePageState extends State<CombatPurchasePage> {
  // late InAppPurchase _inAppPurchase;

  final List<String> _kProductIds = <String>[
    'com.romanlar.read.gear.0.99',
    'com.romanlar.read.gear.1.99',
    'com.romanlar.read.gear.4.99',
    'com.romanlar.read.gear.9.99',
    'com.romanlar.read.gear.19.99',
    'com.romanlar.read.gear.29.99',
    'com.romanlar.read.gear.49.99',
    'com.romanlar.read.gear.99.99',
    'com.romanlar.read.gear.199.99',
    'com.romanlar.read.gear.209.99',
    'com.romanlar.read.gear.349.99'
  ];
  // List<ProductDetails> products = <ProductDetails>[];
  // late StreamSubscription<List<PurchaseDetails>> _subscription;

  _purchaseLog(msg) {
    debugPrint('【支付】$msg');
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('支付'),
      ),
      body: Center(
          child: Column(
        children: [
          ElevatedButton(
              onPressed: () async {
                await initInAppPurchase();
                setState(() {});
              },
              child: const Text('点击初始化')),
          const SizedBox(
            height: 20,
          ),
          // Visibility(
          //   visible: products.isNotEmpty,
          //   child: Column(children: [
          //     const Text('商品列表'),
          //     Wrap(
          //       children: products.map((e) {
          //         return ElevatedButton(
          //             onPressed: () {
          //               // payItems(e);
          //             },
          //             child: Text(e.price));
          //       }).toList(),
          //     )
          //   ]),
          // )
        ],
      )),
    );
  }

  // 初始化服务
  Future<bool> initInAppPurchase() async {
    // try {
    //   _inAppPurchase = InAppPurchase.instance;

    //   //购买回调
    //   Stream<List<PurchaseDetails>> purchaseUpdated =
    //       _inAppPurchase.purchaseStream;
    //   _subscription =
    //       purchaseUpdated.listen((List<PurchaseDetails> purchaseDetailsList) {
    //     _listenToPurchaseUpdated(purchaseDetailsList);
    //   }, onDone: () {
    //     _subscription.cancel();
    //   }, onError: (Object error) {
    //     throw '支付报错回调报错';
    //   });

    //   final bool isAvailable = await _inAppPurchase.isAvailable();

    //   if (!isAvailable) {
    //     throw '服务不可用';
    //   }

      // if (Platform.isIOS) {
      //   final InAppPurchaseStoreKitPlatformAddition iosPlatformAddition =
      //       _inAppPurchase
      //           .getPlatformAddition<InAppPurchaseStoreKitPlatformAddition>();
      //   await iosPlatformAddition.setDelegate(ExamplePaymentQueueDelegate());
      // }
      // 加载待售产品
    //   final ProductDetailsResponse productDetailResponse =
    //       await _inAppPurchase.queryProductDetails(_kProductIds.toSet());

    //   if (productDetailResponse.error != null) {
    //     throw '加载商品列表报错:${productDetailResponse.error}';
    //   }

    //   if (productDetailResponse.productDetails.isEmpty) {
    //     throw '加载商品列表为空';
    //   }

    //   products = productDetailResponse.productDetails;

    //   //价格排序
    //   products = List<ProductDetails>.from(products);
    //   products.sort((a, b) => a.rawPrice.compareTo(b.rawPrice));

    //   return true;
    // } catch (e) {
    //   products = <ProductDetails>[];
    //   _purchaseLog(e);
    //   App.showError(msg:'$e');
      return false;
    // }
  }

  // payItems(ProductDetails productDetail) async {
  //   App.showLoading(title: '支付中…');
  //   if (products.isEmpty) {
  //     App.showToast('No item to be paid was found, please try again later');
  //     return;
  //   }
  //   late PurchaseParam purchaseParam;
  //   if (Platform.isAndroid) {
  //     purchaseParam = GooglePlayPurchaseParam(productDetails: productDetail);
  //   } else {
  //     purchaseParam = PurchaseParam(
  //       productDetails: productDetail,
  //     );
  //   }
  //   _inAppPurchase.buyConsumable(
  //       purchaseParam: purchaseParam, autoConsume: true);
  // }

  //商品回调
  // Future<void> _listenToPurchaseUpdated(
  //     List<PurchaseDetails> purchaseDetailsList) async {
  //   //排序
  //   final sortedList = List.from(purchaseDetailsList);
  //   sortedList.sort((a, b) => (int.tryParse(b.transactionDate ?? '') ?? 0)
  //       .compareTo(int.tryParse(a.transactionDate ?? '') ?? 0));
  //   // 商品列表
  //   for (final PurchaseDetails purchaseDetails in sortedList) {
  //     if (purchaseDetails.status == PurchaseStatus.pending) {
  //       // 请等待支付结果
  //     } else {
  //       //支付错误
  //       if (purchaseDetails.status == PurchaseStatus.error ||
  //           purchaseDetails.status == PurchaseStatus.canceled) {
  //         App.showToast('支付失败：${purchaseDetails.status}');
  //       } else if (purchaseDetails.status == PurchaseStatus.purchased ||
  //           purchaseDetails.status == PurchaseStatus.restored) {
  //         //购买成功  到服务器验证
  //         if (Platform.isAndroid) {
  //           var googleDetail = purchaseDetails as GooglePlayPurchaseDetails;
  //           var originalJson = googleDetail.billingClientPurchase.originalJson;
  //           var signature = googleDetail.billingClientPurchase.signature;
  //           App.showSuccess(
  //               '支付成功：signature => $originalJson signature:$signature');
  //         } else {
  //           var appstoreDetail = purchaseDetails as AppStorePurchaseDetails;
  //           var receipt = appstoreDetail.verificationData.localVerificationData;
  //           App.showSuccess('支付成功：${receipt.substring(0, 20)}');
  //         }
  //       }
  //       if (Platform.isAndroid) {
  //         if (!_kAutoConsume && purchaseDetails.productID == _kConsumableId) {
  //           final InAppPurchaseAndroidPlatformAddition androidAddition =
  //               _inAppPurchase.getPlatformAddition<
  //                   InAppPurchaseAndroidPlatformAddition>();
  //           await androidAddition.consumePurchase(purchaseDetails);
  //         }
  //       }
  //       if (purchaseDetails.pendingCompletePurchase) {
  //         App.hideLoading();
  //         await _inAppPurchase.completePurchase(purchaseDetails);
  //       }
  //     }
    // }
  // }
}
